import { Form } from 'antd-mini/es/Form/form';
import { QueryType } from '../../types/index';
import api from '../../utils/api';

Page({
  data: {
    author: '',
    categoriesId: 1,
  },
  form: new Form(),
  handleRef(ref) {
    this.form.addItem(ref);
  },
  onLoad(query: QueryType) {
    if (query?.userId) {
      this.setData({
        author: query.userId
      })
    }
    api.getCategories({page:1}).then(data => {
      if (Array.isArray(data)&&data.length>0) {
        this.setData({
          categoriesId: data[0].id
        })
      }
    })
  },
  async onUpload(localFile) {
    return await api.upload(localFile);
  },
  async submit() {
    const values = await this.form.submit();
    // 图片处理
    if (values.imageList) {
      let imgStr = '';
      values.imageList.map(item => {
        if (item.url) {
          imgStr += `<img src="${item.url}" alt="图片加载错误" width="100%" />`;
        }
      })
      values.content = values.content + imgStr;
    }
    // 文章发布
    const res = await api.addArticle({
      title: values.title,
      content: values.content,
      author: this.data.author,
      categories: this.data.categoriesId,
      status: 'publish'
    });
    if (res) {
      my.navigateTo({
        url: `/pages/list/list`
      })
    }
  }
});
